package com.atguigu.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.atguigu.entity.Role;
import com.atguigu.service.PermissionService;
import com.atguigu.service.RoleService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "/role")
public class RoleController extends BaseController {
    @Reference
    private RoleService roleService;
    @Reference
    private PermissionService permissionService;

    @PreAuthorize("hasAuthority('role.show')")
    @RequestMapping
    public String index(ModelMap model, HttpServletRequest request) {
        // 获取请求参数
        Map<String, Object> filters = getFilters(request);
        model.addAttribute("filters", filters);
        // 调用 roleService 中分页及带条件查询的方法
        PageInfo<Role> page = roleService.findPage(filters);
        model.addAttribute("page", page);

        return "role/index";
    }

    // 去新增页面
    @GetMapping("/create")
    public String create() {
        return "role/create";
    }
    // 保存添加的内容
    @PostMapping("/save")
    public String save(Role role, HttpServletRequest request) {
        roleService.insert(role);
        return "common/successPage";
    }

    @GetMapping("/edit/{id}")
    public String edit(ModelMap model, @PathVariable Long id) {
        Role role = roleService.getById(id);
        model.addAttribute("role", role);
        return "role/edit";
    }

    @PostMapping("/update")
    public String update(Role role) {
        roleService.update(role);
        return "common/successPage";
    }

    @GetMapping("/delete/{id}")
    public String delete(@PathVariable Long id) {
        roleService.delete(id);
        return "redirect:/role";
    }
    // 去分配角色权限的页面
    @GetMapping("/assignShow/{roleId}")
    public String toAssignShowPage(@PathVariable Long roleId,Map map) {
        // 带roleId（角色ID）
        map.put("roleId", roleId);
        List<Map<String,Object>> zNodes = permissionService.findPermissionsByRoleId(roleId);
        map.put("zNodes", zNodes);
        return "role/assignShow";
    }
    // 分配角色权限
    @PostMapping("/assignPermission")
    public String assignPermission(Long roleId,Long[] permissionIds) {
        // 调用分配权限的方法
        permissionService.assignPermission(roleId, permissionIds);
        return "common/successPage";
    }
}